package iclickhouse

import (
	"gitee.com/tietang/terrace-go/v2/base"
	"gitee.com/tietang/terrace-go/v2/base/starter/ilogrus"
	_ "github.com/mailru/go-clickhouse/v2"
	log "github.com/sirupsen/logrus"
	"github.com/tietang/dbx"
	"github.com/tietang/props/v3/kvs"
)

// Dbx SQL数据库ORM框架实例
var clickhouse *dbx.Database

func Clickhouse() *dbx.Database {
	base.Check(clickhouse)
	return clickhouse
}

func RegisterTable(model interface{}, tableName string) {
	clickhouse.RegisterTable(model, tableName)
}

// 配置示列：

//[clickhouse]
//driverName = chhttp
//protocol = http
//host = 10.99.66.93:8123
//database = mo
//user = admin
//password = N+JeozDXx5b3JxQrLQmTsLbXqo8N0YjS
//;连接池配置
//connMaxLifetime = 12h
//maxIdleConns = 1
//maxOpenConns = 3
//loggingEnabled = true
//;数据源参数配置
//options.read_timeout = 10s
//options.write_timeout = 20s

type DbxClickhouseStarter struct {
	base.BaseStarter
	ConfigPrefix string
	settings     dbx.Settings
}

// 初始化DbxDatabase ，并设置全局DbxDatabase
func (s *DbxClickhouseStarter) Setup(ctx base.StarterContext) {
	conf := ctx.Props()
	settings := dbx.Settings{}
	if s.ConfigPrefix == "" {
		s.ConfigPrefix = "clickhouse"
	}
	err := kvs.Unmarshal(conf, &settings, s.ConfigPrefix)
	if err != nil {
		panic(err)
	}
	log.Debugf("%+v", settings)
	log.Debugf("clickhouse.ConnectionURL: %s", settings.ShortDataSourceName())
	clickhouse, err = dbx.Open(settings)
	if err != nil {
		panic(err)
	}
	clickhouse.SetLogger(ilogrus.NewDbxLogrusLogger())
	s.settings = settings
}

func (s *DbxClickhouseStarter) Stop(ctx base.StarterContext) {
	Clickhouse().Close()
	log.Info(" dbx shutdown on：", s.settings.ShortDataSourceName())
}
